import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, ScrollView, SafeAreaView, Image, TextInput, Alert, Linking } from 'react-native';
import { Stack, useRouter } from 'expo-router';
import { Ionicons, MaterialIcons, MaterialCommunityIcons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import axios from 'axios';
import DropDownPicker from 'react-native-dropdown-picker';
import Constants from 'expo-constants';
import api from '../../services/userService';

export default function HelpAndFeedbackScreen() {
  const [activeTab, setActiveTab] = useState('help'); // 'help' 或 'feedback'
  const router = useRouter();
  
  return (
    <SafeAreaView className="flex-1 bg-gray-50 dark:bg-gray-900">
      {/* 分段控制器 */}
      <View className="flex-row bg-white border-b border-gray-200 dark:bg-gray-800 dark:border-gray-700">
        <TouchableOpacity 
          className={`flex-1 py-4 items-center ${activeTab === 'help' ? 'border-b-2 border-blue-500' : ''}`}
          onPress={() => setActiveTab('help')}
        >
          <Text className={`text-base ${activeTab === 'help' ? 'text-blue-500 font-bold' : 'text-gray-600 dark:text-gray-300'}`}>帮助中心</Text>
        </TouchableOpacity>
        <TouchableOpacity 
          className={`flex-1 py-4 items-center ${activeTab === 'feedback' ? 'border-b-2 border-blue-500' : ''}`}
          onPress={() => setActiveTab('feedback')}
        >
          <Text className={`text-base ${activeTab === 'feedback' ? 'text-blue-500 font-bold' : 'text-gray-600 dark:text-gray-300'}`}>问题反馈</Text>
        </TouchableOpacity>
      </View>
      
      {/* 内容区域 */}
      {activeTab === 'help' ? (
        <HelpCenterScreen />
      ) : (
        <FeedbackScreen />
      )}
    </SafeAreaView>
  );
}

// 帮助中心页面
function HelpCenterScreen() {
  // 常见问题状态管理
  const [expandedQuestions, setExpandedQuestions] = useState<string[]>([]);
  
  // 切换问题折叠状态
  const toggleQuestion = (questionId: string) => {
    setExpandedQuestions(prev => 
      prev.includes(questionId) 
        ? prev.filter(id => id !== questionId) 
        : [...prev, questionId]
    );
  };
  
  // 处理拨打电话咨询
  const handlePhoneConsult = () => {
    Linking.openURL('tel:15794807263').catch(err => {
      Alert.alert('提示', '无法打开拨号界面，请手动拨打电话');
    });
  };
  
  // 常见问题数据
  const faqData = [
    {
      id: 'profile',
      question: '如何修改个人资料?',
      answer: '在个人主页点击"编辑个人资料"按钮，即可进入编辑页面修改你的个人信息，包括头像、昵称、学术信息等。修改完成后，点击保存即可更新资料。'
    },
    {
      id: 'post',
      question: '如何发布帖子和参与讨论?',
      answer: '点击底部导航栏中的"+"按钮，即可创建新帖子。在帖子详情页面下方的评论区，你可以发表评论参与讨论。你还可以点赞、收藏感兴趣的内容。'
    },
    {
      id: 'group',
      question: '如何加入或创建社团?',
      answer: '在社区列表页面，你可以浏览所有可加入的社团，点击感兴趣的社团进入详情页，然后点击"加入"按钮申请加入。如需创建新社团，请联系学生会或管理员申请创建权限。'
    },
    {
      id: 'privacy',
      question: '账号安全和隐私设置',
      answer: '在个人主页点击"隐私设置"，你可以控制谁能查看你的个人资料、联系方式，以及谁能与你互动。定期修改密码并开启双因素认证，可以提高账号安全性。'
    },
    {
      id: 'report',
      question: '如何举报不当内容?',
      answer: '如发现违规内容，可点击帖子或评论右上角的"更多"按钮，选择"举报"选项，请详细说明举报原因，管理员会尽快审核处理。我们鼓励共同维护社区环境的和谐。'
    }
  ];
  
  // 处理相关资源点击
  const handleResourceClick = (resourceType: string) => {
    Alert.alert("提示", "该功能正在开发中，敬请期待", [
      { text: "关闭", style: "cancel" }
    ]);
  };

  return (
    <ScrollView className="flex-1 p-4 bg-gray-50 dark:bg-gray-900">
      {/* 常见问题部分 */}
      <View className="bg-white rounded-xl p-4 mb-4 shadow-sm dark:bg-gray-800">
        <Text className="text-lg font-bold mb-4 text-gray-800 dark:text-gray-100">常见问题</Text>
        
        {faqData.map(item => (
          <View key={item.id} className="mb-4 border-b border-gray-100 pb-2 dark:border-gray-700">
            <TouchableOpacity 
              className="flex-row justify-between items-center py-2"
              onPress={() => toggleQuestion(item.id)}
              activeOpacity={0.7}
            >
              <Text className="text-base font-medium text-gray-800 flex-1 pr-2 dark:text-gray-200">{item.question}</Text>
              <MaterialIcons 
                name={expandedQuestions.includes(item.id) ? "keyboard-arrow-up" : "keyboard-arrow-down"} 
                size={24} 
                color="#666" 
              />
            </TouchableOpacity>
            
            {expandedQuestions.includes(item.id) && (
              <View className="mt-1 p-3 bg-gray-50 rounded-lg dark:bg-gray-700">
                <Text className="text-sm text-gray-600 leading-5 dark:text-gray-300">{item.answer}</Text>
              </View>
            )}
          </View>
        ))}
      </View>
      
      {/* 联系客服部分 */}
      <View className="bg-white rounded-xl p-4 mb-4 shadow-sm dark:bg-gray-800">
        <Text className="text-lg font-bold mb-4 text-gray-800 dark:text-gray-100">联系客服</Text>
        
        <View className="flex-row items-center mb-5 py-1">
          <View className="w-10 h-10 rounded-full bg-blue-500 justify-center items-center">
            <MaterialIcons name="email" size={24} color="#fff" />
          </View>
          <View className="ml-4 flex-1">
            <Text className="text-sm font-medium text-gray-500 dark:text-gray-400">邮箱</Text>
            <Text className="text-base text-gray-800 mt-0.5 dark:text-gray-200">202241308@stu.qmu.edu.cn</Text>
          </View>
        </View>
        
        <View className="flex-row items-center mb-5 py-1">
          <View className="w-10 h-10 rounded-full bg-green-500 justify-center items-center">
            <MaterialIcons name="phone" size={24} color="#fff" />
          </View>
          <View className="ml-4 flex-1">
            <Text className="text-sm font-medium text-gray-500 dark:text-gray-400">电话</Text>
            <Text className="text-base text-gray-800 mt-0.5 dark:text-gray-200">15794807263</Text>
            <Text className="text-xs text-gray-500 mt-0.5 dark:text-gray-400">周一至周五 9:00-17:00</Text>
          </View>
        </View>
        
        <View className="flex-row items-center mb-2 py-1">
          <View className="w-10 h-10 rounded-full bg-purple-600 justify-center items-center">
            <MaterialCommunityIcons name="chat-processing" size={24} color="#fff" />
          </View>
          <View className="ml-4 flex-1">
            <Text className="text-sm font-medium text-gray-500 dark:text-gray-400">在线客服</Text>
            <Text className="text-base text-gray-800 mt-0.5 dark:text-gray-200">每天 8:00-22:00</Text>
            <TouchableOpacity className="bg-blue-500 rounded-lg py-2 px-4 items-center mt-2 self-start" onPress={handlePhoneConsult}>
              <Text className="text-white font-medium text-sm">立即咨询</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
      
      {/* 相关资源部分 */}
      <View className="bg-white rounded-xl p-4 mb-4 shadow-sm dark:bg-gray-800">
        <Text className="text-lg font-bold mb-4 text-gray-800 dark:text-gray-100">相关资源</Text>
        
        <TouchableOpacity 
          className="flex-row items-center p-4 border border-gray-100 rounded-lg mb-2 bg-white dark:bg-gray-800 dark:border-gray-700"
          onPress={() => handleResourceClick('guide')}
        >
          <View className="w-10 h-10 rounded-full bg-orange-500 justify-center items-center mr-4">
            <MaterialIcons name="menu-book" size={24} color="#fff" />
          </View>
          <Text className="text-base font-medium text-gray-800 flex-1 dark:text-gray-200">使用指南</Text>
          <MaterialIcons name="chevron-right" size={24} color="#ccc" />
        </TouchableOpacity>
        
        <TouchableOpacity 
          className="flex-row items-center p-4 border border-gray-100 rounded-lg mb-2 bg-white dark:bg-gray-800 dark:border-gray-700"
          onPress={() => handleResourceClick('rules')}
        >
          <View className="w-10 h-10 rounded-full bg-blue-500 justify-center items-center mr-4">
            <MaterialIcons name="gavel" size={24} color="#fff" />
          </View>
          <Text className="text-base font-medium text-gray-800 flex-1 dark:text-gray-200">社区规范</Text>
          <MaterialIcons name="chevron-right" size={24} color="#ccc" />
        </TouchableOpacity>
        
        <TouchableOpacity 
          className="flex-row items-center p-4 border border-gray-100 rounded-lg mb-2 bg-white dark:bg-gray-800 dark:border-gray-700"
          onPress={() => handleResourceClick('privacy')}
        >
          <View className="w-10 h-10 rounded-full bg-gray-500 justify-center items-center mr-4">
            <MaterialIcons name="security" size={24} color="#fff" />
          </View>
          <Text className="text-base font-medium text-gray-800 flex-1 dark:text-gray-200">隐私政策</Text>
          <MaterialIcons name="chevron-right" size={24} color="#ccc" />
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
}

// 反馈提交页面
function FeedbackScreen() {
  const [feedbackType, setFeedbackType] = useState('功能异常');
  const [feedbackContent, setFeedbackContent] = useState('');
  const [contactInfo, setContactInfo] = useState('');
  const [images, setImages] = useState<ImagePicker.ImagePickerAsset[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [myFeedbacks, setMyFeedbacks] = useState([]);
  const [showHistory, setShowHistory] = useState(false);
  
  // 下拉选择框状态
  const [open, setOpen] = useState(false);
  const [items, setItems] = useState([
    { label: '功能异常', value: '功能异常' },
    { label: '使用建议', value: '使用建议' },
    { label: '内容问题', value: '内容问题' },
    { label: '其他', value: '其他' },
  ]);
  
  // 自定义输入
  const [customValue, setCustomValue] = useState('');
  // 是否显示自定义输入框
  const [showCustomInput, setShowCustomInput] = useState(false);
  
  // 处理自定义输入
  const handleCustomValue = (text: string) => {
    setCustomValue(text);
  };
  
  // 检查是否是自定义值
  const isCustomValue = () => {
    return !items.some(item => item.value === feedbackType);
  };

  // 选择图片
  const pickImage = async () => {
    if (images.length >= 5) {
      Alert.alert('提示', '最多只能上传5张图片');
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ["images"],
      allowsEditing: false,
      quality: 0.8,
      allowsMultipleSelection: true,
      selectionLimit: 5 - images.length,
    });

    if (!result.canceled) {
      const newImages = [...images, ...result.assets];
      if (newImages.length > 5) {
        Alert.alert('提示', '最多只能上传5张图片，已自动选择前5张');
        setImages(newImages.slice(0, 5));
      } else {
        setImages(newImages);
      }
    }
  };

  // 删除图片
  const removeImage = (index: number) => {
    const newImages = [...images];
    newImages.splice(index, 1);
    setImages(newImages);
  };

  // 提交反馈
  const submitFeedback = async () => {
    if (!feedbackContent.trim()) {
      Alert.alert('提示', '请填写反馈内容');
      return;
    }

    if (showCustomInput && !customValue.trim()) {
      Alert.alert('提示', '请输入自定义反馈类型');
      return;
    }

    setIsSubmitting(true);

    try {
      const formData = new FormData();
      // 如果显示自定义输入框，则使用自定义输入
      formData.append('type', showCustomInput ? customValue : feedbackType);
      formData.append('content', feedbackContent);
      
      if (contactInfo.trim()) {
        formData.append('contactInfo', contactInfo);
      }

      // 添加图片文件
      images.forEach((image, index) => {
        const localUri = image.uri;
        const filename = localUri.split('/').pop() || `image${index}.jpg`;
        
        // 从URI获取文件扩展名
        const match = /\.(\w+)$/.exec(filename);
        const type = match ? `image/${match[1]}` : 'image/jpeg';
        
        // @ts-ignore
        formData.append('files', {
          uri: localUri,
          name: filename,
          type
        });
      });

      // 发送请求
      const response = await api.post('/api/feedback/add/with-files', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      if (response.data.code === 0) {
        Alert.alert('提示', '反馈提交成功', [
          { text: '确定', onPress: () => {
            setFeedbackContent('');
            setContactInfo('');
            setImages([]);
            setShowHistory(true);
            loadMyFeedbacks();
          }}
        ]);
      } else {
        Alert.alert('提交失败', response.data.message || '请稍后再试');
      }
    } catch (error: any) {
      console.error('提交反馈失败:', error);
      Alert.alert('提交失败', error.response?.data?.message || '网络错误，请稍后再试');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 加载我的反馈历史
  const loadMyFeedbacks = async () => {
    try {
      const response = await api.post('/api/feedback/my/list/page', {
        current: 1,
        pageSize: 10
      });

      if (response.data.code === 0) {
        setMyFeedbacks(response.data.data.records || []);
      }
    } catch (error) {
      console.error('获取反馈历史失败:', error);
    }
  };

  // 组件首次加载时获取反馈历史
  useEffect(() => {
    loadMyFeedbacks();
  }, []);
  
  // 初始化自定义输入框状态
  useEffect(() => {
    setShowCustomInput(feedbackType === '其他');
  }, []);

  // 渲染我的反馈历史列表项
  const renderFeedbackItem = (item: any) => {
    const statusColors: any = {
      'pending': '#FFBB33',
      'processing': '#FFBB33', 
      'resolved': '#33CC66'
    };
    
    const statusText: any = {
      'pending': '处理中',
      'processing': '处理中',
      'resolved': '已完成'
    };

    return (
      <View key={item.id} className="bg-white rounded-lg p-4 mb-2 border border-gray-100 dark:bg-gray-800 dark:border-gray-700">
        <View className="flex-row justify-between items-center mb-1">
          <Text className="text-base font-medium text-gray-800 flex-1 dark:text-gray-200" numberOfLines={1}>
            {item.content && item.content.length > 20 ? item.content.substring(0, 20) + '...' : item.content}
          </Text>
          <View className="px-2 py-1 rounded" style={{ backgroundColor: statusColors[item.status] || '#999' }}>
            <Text className="text-white text-xs font-medium">{statusText[item.status] || '未知'}</Text>
          </View>
        </View>
        <Text className="text-xs text-gray-500 mb-2 dark:text-gray-400">提交于{item.createTime && item.createTime.substring(0, 10)}</Text>
        
        {item.replyContent && (
          <View className="mt-2 bg-gray-50 p-3 rounded-md dark:bg-gray-700">
            <Text className="text-sm font-medium text-gray-600 mb-1 dark:text-gray-300">官方回复：</Text>
            <Text className="text-sm text-gray-800 dark:text-gray-200">{item.replyContent}</Text>
          </View>
        )}
      </View>
    );
  };

  return (
    <ScrollView className="flex-1 p-4 bg-gray-50 dark:bg-gray-900">
      {!showHistory ? (
        <>
          <View className="bg-white rounded-xl p-4 mb-4 shadow-sm dark:bg-gray-800">
            <Text className="text-lg font-bold mb-4 text-gray-800 dark:text-gray-100">提交反馈</Text>
            
            <Text className="text-sm font-medium text-gray-600 mb-1 mt-3 dark:text-gray-300">反馈类型</Text>
            <View className="z-50 mb-3">
              <DropDownPicker
                open={open}
                value={feedbackType}
                items={items}
                setOpen={setOpen}
                setValue={(value: any) => {
                  setFeedbackType(value);
                  if (value === '其他') {
                    setCustomValue('');
                    setShowCustomInput(true);
                  } else {
                    setShowCustomInput(false);
                  }
                }}
                setItems={setItems}
                placeholder="选择反馈类型"
                style={{
                  backgroundColor: '#f3f4f6',
                  borderColor: '#e5e7eb',
                  borderRadius: 8,
                  minHeight: 45
                }}
                dropDownContainerStyle={{
                  backgroundColor: '#ffffff',
                  borderColor: '#e5e7eb',
                  borderRadius: 8,
                  zIndex: 1000,
                  elevation: 3
                }}
                textStyle={{
                  fontSize: 16,
                  color: '#1f2937'
                }}
                listItemLabelStyle={{
                  color: '#1f2937'
                }}
                theme="LIGHT"
                listMode="SCROLLVIEW"
                scrollViewProps={{
                  nestedScrollEnabled: true
                }}
                ArrowDownIconComponent={({style}) => <Ionicons name="chevron-down" size={20} color="#666" />}
                ArrowUpIconComponent={({style}) => <Ionicons name="chevron-up" size={20} color="#666" />}
                showTickIcon={false}
                closeAfterSelecting={true}
                searchable={false}
                maxHeight={200}
              />
            </View>
            
            {showCustomInput && (
              <View className="mb-3">
                <TextInput
                  className="bg-gray-100 border border-gray-200 rounded-lg p-3 text-base text-gray-800 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
                  placeholder="请输入自定义反馈类型"
                  placeholderTextColor="#999"
                  value={customValue}
                  onChangeText={handleCustomValue}
                />
              </View>
            )}
            
            <Text className="text-sm font-medium text-gray-600 mb-1 mt-2 dark:text-gray-300">问题描述</Text>
            <TextInput
              className="bg-gray-100 border border-gray-200 rounded-lg p-3 text-base text-gray-800 min-h-[120px] dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
              multiline
              numberOfLines={5}
              placeholder="请详细描述你遇到的问题或建议..."
              placeholderTextColor="#999"
              value={feedbackContent}
              onChangeText={setFeedbackContent}
            />
            
            <Text className="text-sm font-medium text-gray-600 mb-1 mt-4 dark:text-gray-300">图片上传 (可选)</Text>
            <View className="flex-row flex-wrap mt-1">
              {images.map((image, index) => (
                <View key={index} className="w-24 h-24 m-1 rounded-lg overflow-hidden relative">
                  <Image source={{ uri: image.uri }} className="w-full h-full" />
                  <TouchableOpacity 
                    className="absolute top-1 right-1 bg-white bg-opacity-80 rounded-full"
                    onPress={() => removeImage(index)}
                  >
                    <Ionicons name="close-circle" size={24} color="#FF6B6B" />
                  </TouchableOpacity>
                </View>
              ))}
              
              {images.length < 5 && (
                <TouchableOpacity 
                  className="w-24 h-24 border border-gray-200 border-dashed rounded-lg justify-center items-center bg-gray-50 m-1 dark:bg-gray-700 dark:border-gray-600"
                  onPress={pickImage}
                >
                  <Ionicons name="cloud-upload-outline" size={32} color="#ccc" />
                  <Text className="text-xs text-gray-500 mt-1 dark:text-gray-400">点击上传图片</Text>
                  <Text className="text-[10px] text-gray-400 mt-0.5 text-center dark:text-gray-500">支持JPG、PNG格式，最大10MB</Text>
                </TouchableOpacity>
              )}
            </View>
            
            <Text className="text-sm font-medium text-gray-600 mb-1 mt-4 dark:text-gray-300">联系方式 (可选)</Text>
            <TextInput
              className="bg-gray-100 border border-gray-200 rounded-lg p-3 text-base text-gray-800 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
              placeholder="邮箱或手机号，方便我们联系你"
              placeholderTextColor="#999"
              value={contactInfo}
              onChangeText={setContactInfo}
            />
          </View>
          
          <View className="mb-8">
            <TouchableOpacity 
              className="bg-blue-500 rounded-lg p-4 items-center mb-2"
              onPress={submitFeedback}
              disabled={isSubmitting}
            >
              <Text className="text-white text-base font-bold">
                {isSubmitting ? '提交中...' : '提交反馈'}
              </Text>
            </TouchableOpacity>
            
            <TouchableOpacity 
              className="bg-white rounded-lg p-4 items-center border border-gray-200 dark:bg-gray-800 dark:border-gray-700"
              onPress={() => setShowHistory(true)}
            >
              <Text className="text-gray-600 text-base dark:text-gray-300">我的反馈历史</Text>
            </TouchableOpacity>
          </View>
        </>
      ) : (
        <View className="flex-1">
          <View className="flex-row justify-between items-center mb-4">
            <Text className="text-lg font-bold text-gray-800 dark:text-gray-100">我的反馈历史</Text>
            <TouchableOpacity onPress={() => setShowHistory(false)}>
              <Text className="text-blue-500 text-base font-medium">新建反馈</Text>
            </TouchableOpacity>
          </View>
          
          {myFeedbacks.length > 0 ? (
            myFeedbacks.map((item: any) => renderFeedbackItem(item))
          ) : (
            <View className="items-center justify-center py-12">
              <Ionicons name="document-text-outline" size={64} color="#ccc" />
              <Text className="text-gray-500 text-base mt-3 dark:text-gray-400">暂无反馈记录</Text>
            </View>
          )}
        </View>
      )}
    </ScrollView>
  );
}